package com.unisedu.oa.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.json.JSONObject;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.Principal;

public class JsonUtils {


    public static String formatResult(int code, String message, Object data) {
        JSONObject json = new JSONObject();
        json.put("code", code);
        json.put("message", message);
        json.put("data", data);
        return json.toString();
    }

    public static void formatResult(HttpServletResponse response, int code, String message) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Type","application/json");
        PrintWriter writer = response.getWriter();
        String json = formatResult(code,message,null);
        writer.write(json);
        writer.close();
    }

    public static JSONObject toJsonString(Object obj)  {
        ObjectMapper mapper = new ObjectMapper();
        try {

            return new JSONObject(mapper.writeValueAsString(obj));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }

    }
}
